package cn.dankal.flyaudio

import android.content.Intent
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.util.TypedValue
import android.view.MotionEvent
import android.view.View
import android.widget.TableLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import api.UserServiceFactory
import cn.dankal.basiclib.DKUserManager
import cn.dankal.basiclib.DankalApplication
import cn.dankal.basiclib.base.activity.BaseActivity
import cn.dankal.basiclib.base.fragment.BaseFragment
import cn.dankal.basiclib.pojo.UserInfoBean
import cn.dankal.basiclib.protocol.LoginProtocol
import cn.dankal.basiclib.protocol.MainProtocol
import cn.dankal.basiclib.rx.AbstractDialogSubscriber
import cn.dankal.basiclib.util.*
import cn.dankal.basiclib.widget.CommonDialog
import cn.dankal.basiclib.widget.statubar.QMUIStatusBarHelper
import cn.dankal.business.Constants
import cn.dankal.business.eventbus.OFFLoginEvent
import cn.dankal.flyaudio.activity.search.SearchActivity
import cn.dankal.flyaudio.configs.TestData
import cn.dankal.flyaudio.home.ActivityFragment
import cn.dankal.flyaudio.home.CurrentFragment
import cn.dankal.flyaudio.home.HomeFragment
import cn.dankal.flyaudio.home.InformationFragment
import cn.dankal.flyaudio.login.LoginActivity
import cn.dankal.flyaudio.pop.FriendAddPop
import cn.dankal.flyaudio.pop.HomeScanPop
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils
import com.google.android.material.tabs.TabLayout
import com.jeremyliao.liveeventbus.LiveEventBus
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Permission
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.common.Constant
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import java.lang.reflect.Field

public class EyeFragment : BaseFragment() {


    override fun getLayoutId(): Int = R.layout.activity_main

    lateinit var commonDialog: CommonDialog

    override fun initComponents() {

        EventBus.getDefault().post(OFFLoginEvent())
//
//        DankalApplication.setLogin(true)
//
//        val currentUser = SharePreferenceManager.getCurrentUser()
//        Log.d("EyeFragment", "账号:" + currentUser)
//        TestData.setUser(currentUser)

        if (!DKUserManager.isLogined()) {
            startActivity(Intent(activity, LoginActivity::class.java))
            activity?.finish()
            return
        }
        iv_friend_add.setOnClickListener {
            HomeScanPop(context).showPopupWindow(R.id.iv_friend_add)
//            activity?.startActivityForResult(Intent(context, CaptureActivity::class.java), Constants.SCAN)
        }
        LiveEventBus.get("to_home_activity1", String::class.java).observe(this, Observer<String?> {
            Handler().postDelayed(Runnable {
                select(Constants.ITEM_ACTIVITY);
            },200)

        }
        )
        tv_search.setOnClickListener {
            ActivityUtils.startActivity(SearchActivity::class.java)
        }
        mSectionsPagerAdapter = SectionsPagerAdapter(childFragmentManager)
        // Set up the ViewPager with the sections adapter.
        container.adapter = mSectionsPagerAdapter
        container.offscreenPageLimit = 4
        container.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabs))
        //tabs.addOnTabSelectedListener(TabLayout.ViewPagerOnTabSelectedListener(container))
        tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.let {
                    // 默认切换的时候，会有一个过渡动画，设为false后，取消动画，直接显示
                    container.setCurrentItem(tab.getPosition(), false)
                    container.setCurrentItem(tab.getPosition())
                    setSelect(tab.position)
                }
            }
        })

        container.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                when (position) {
                    Constants.ITEM_HOME -> {
//                        setSelect(0)
                        QMUIStatusBarHelper.setStatusBarLightMode(activity)
                    }
                    Constants.ITEM_ACTIVITY -> {
//                        setSelect(1)
                        QMUIStatusBarHelper.setStatusBarLightMode(activity)
                    }
                    Constants.ITEM_INFORMATION -> {
//                        setSelect(2)
                        QMUIStatusBarHelper.setStatusBarLightMode(activity)
                    }
                    Constants.ITEM_CURRENT -> {
//                        setSelect(3)
                        QMUIStatusBarHelper.setStatusBarLightMode(activity)
                    }
                }
            }
        })

        tabs.setSelectedTabIndicatorHeight(0)
        tabs.addTab(tabs.newTab().setCustomView(createTab("推荐")).setTag(Constants.ITEM_HOME));

        tabs.addTab(tabs.newTab().setCustomView(createTab("活动")).setTag(Constants.ITEM_ACTIVITY));

        tabs.addTab(tabs.newTab().setCustomView(createTab("资讯")).setTag(Constants.ITEM_INFORMATION));

        tabs.addTab(tabs.newTab().setCustomView(createTab("此刻")).setTag(Constants.ITEM_CURRENT));


        requestPermission()
        setSelect(0)
        getUserInfo()
    }

    private fun setSelect(poi: Int) {
        for (i in 0 until tabs.tabCount) {
            val view = tabs.getTabAt(i)?.customView;
            view?.findViewById<TextView>(R.id.tab_text)?.setTextColor(resources.getColor(R.color.color_2D343D))
            view?.findViewById<TextView>(R.id.tab_text)?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16F)
            view?.findViewById<TextView>(R.id.tab_text)?.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            view?.findViewById<View>(R.id.tab_line)?.visibility = View.GONE
        }
        val currentView = tabs.getTabAt(poi)?.customView;
        currentView?.findViewById<TextView>(R.id.tab_text)?.setTextColor(resources.getColor(R.color.colorPrimary))
        currentView?.findViewById<TextView>(R.id.tab_text)?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18F)
        currentView?.findViewById<TextView>(R.id.tab_text)?.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        currentView?.findViewById<View>(R.id.tab_line)?.visibility = View.VISIBLE
    }

    private fun createTab(tab: String): View {
        val tabView = layoutInflater.inflate(R.layout.item_home_tab, null);
        tabView.findViewById<TextView>(R.id.tab_text).setText(tab)
        return tabView;
    }

    /**
     * 获取个人用户信息
     */
    private fun getUserInfo() {
        if (DKUserManager.isLogined()) {
            UserServiceFactory.user_info()
                    .subscribe(object : AbstractDialogSubscriber<UserInfoBean>(this) {
                        override fun onNext(userInfo: UserInfoBean) {
                            DKUserManager.updateUserInfo(userInfo)
                        }

                        override fun onSubscribe(d: Disposable) {
                        }
                    })
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    /** 反射获取tabview  */
    private fun getTabView(tabLayout: TabLayout, index: Int): View? {
        val tab = tabLayout.getTabAt(index) ?: return null
        var tabView: View? = null
        try {
            val view: Field = TabLayout.Tab::class.java.getDeclaredField("mView")
            view.isAccessible = true
            tabView = view.get(tab) as View
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return tabView
    }

    private fun requestPermission() {
        PermissionUtils.permission(PermissionConstants.PHONE,PermissionConstants.CAMERA,PermissionConstants.STORAGE)
                .callback(object:PermissionUtils.SimpleCallback{
                    override fun onGranted() {

                    }

                    override fun onDenied() {
                        val builder = CommonDialog.Builder(activity)
                        builder.setTitle("禁止飞歌获取权限会影响到您的正常使用")

                        builder.setNegativeButton("残忍拒绝",
                                resources.getColor(R.color.color14)) {
                            ToastUtils.showShort("获取权限失败，请到设置中手动开启权限")
                            DKHandler(activity).postDelayed({ activity?.finish() }, 1000)
                            commonDialog.dismiss()
                        }
                        builder.setPositiveButton("同意开启",
                                resources.getColor(R.color.colorPrimary)) {
                            toSelfSetting()
                            commonDialog.dismiss()
                        }
                        commonDialog = builder.create()
                        commonDialog.show()
                    }

                }).request()
//        AndPermission.with(this)
//                .runtime()
//                .permission(Permission.CALL_PHONE, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE)
//                .onDenied {
//
//                }.start()
    }

    private fun toSelfSetting() {
        var mIntent = Intent()
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= 9) {
            mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            mIntent.setData(Uri.fromParts("package", activity?.getPackageName(), null))
        } else if (Build.VERSION.SDK_INT <= 8) {
            mIntent.setAction(Intent.ACTION_VIEW)
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails")
            mIntent.putExtra("com.android.settings.ApplicationPkgName", activity?.getPackageName())
        }
        startActivity(mIntent)
    }

    private var mSectionsPagerAdapter: SectionsPagerAdapter? = null


    inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

        override fun getItem(position: Int): Fragment {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            when (position) {
                Constants.ITEM_HOME -> {
                    return HomeFragment.newInstance()
                }
                Constants.ITEM_ACTIVITY -> {
                    return ActivityFragment.newInstance()
                }
                Constants.ITEM_INFORMATION -> {
                    return InformationFragment.newInstance()
                }
                Constants.ITEM_CURRENT -> {
                    return CurrentFragment.newInstance()
                }
            }
            return HomeFragment.newInstance()
        }

        override fun getCount(): Int {
            // Show 3 total pages.
            return 4
        }
    }

    fun select(position: Int) {
        container.setCurrentItem(position, true)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Constants.SCAN && resultCode == BaseActivity.RESULT_OK && data != null) {

            //扫码内容
            val result = data.getStringExtra(Constant.CODED_CONTENT)

            if (result.contains("native://cn.dankal.flyaudio/activityid=")) {
                val resultValue = result.split("native://cn.dankal.flyaudio/activityid=")[1]
                ARouter.getInstance().build(MainProtocol.ACTIVITY_DETAIL)
                        .withString(Constants.UUID, resultValue)
                        .navigation()
                return
            } else {
                showToast("暂无相关信息")
            }
        }
    }
}